package lime49.lockcrypt.mobile;
import java.util.*;

public class Utils {
    /**
     * 
     * @param original
     * @param separator
     * @return
     */
    public static String[] split(String original, String separator) {
        Vector nodes = new Vector();

        // Parse nodes into vector
        int index = original.indexOf(separator);
        while(index>=0) {
            nodes.addElement(original.substring(0, index).trim());
            original = original.substring(index+separator.length()).trim();
            index = original.indexOf(separator);
        }
        // Get the last node
        nodes.addElement(original);

        // Create splitted string array
        String[] result = new String[nodes.size()];
        if(nodes.size()>0) {
            for(int loop=0; loop<nodes.size(); loop++) {
                result[loop] = (String)nodes.elementAt(loop);
            }
        }
        return result;
    }
    /**
     * Returns the bytes for the MD5 hash of the spullied key
     * @param keystring The key for which to calculate the hash bytes
     * @return The generated hash bytes
     * @throws java.lang.Exception
     */
    public static byte[] getKeySpec(String keystring) throws Exception {
        byte[] key = new byte[16];
        MD5 hashMD5 = new MD5();
        hashMD5.Update(keystring.getBytes());
        byte[] hashbytes = hashMD5.Final();
        return hashbytes;
    }
    
    /**
     * String replace method for J2ME
     * @param haystack The text to search
     * @param needle The text to replace
     * @param replacement The new text
     * @return The string, with all instances of 'needle' replaced with 'replacement'
     */
    public static String replace(String haystack, String needle, String replacement) {
        StringBuffer sb = new StringBuffer();
 
        // Search
        int searchStringPos = haystack.indexOf(needle);
        int startPos = 0;
        int searchStringLength = needle.length();
 
        // Iterate to add string
        while(searchStringPos != -1) {
            sb.append(haystack.substring(startPos, searchStringPos)).append(replacement);
            startPos = searchStringPos + searchStringLength;
            searchStringPos = haystack.indexOf(needle, startPos);
        }
        // Create string
        sb.append(haystack.substring(startPos,haystack.length()));
        return sb.toString();
    } 
}
